package com.lixin.smartclassroom.ui.home.tab2.activity

import android.graphics.Color
import android.net.Uri
import android.provider.MediaStore
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.drake.brv.utils.bindingAdapter
import com.drake.channel.receiveEvent
import com.drake.net.utils.scopeDialog
import com.drake.net.utils.scopeNetLife
import com.drake.tooltip.dialog.BubbleDialog
import com.lixin.smartclassroom.R
import com.lixin.smartclassroom.api.addchangguan
import com.lixin.smartclassroom.api.addcourse
import com.lixin.smartclassroom.api.addyanxuecourse
import com.lixin.smartclassroom.api.updatecourse
import com.lixin.smartclassroom.api.updateyanxuecourse
import com.lixin.smartclassroom.api.updatezhuticourse
import com.lixin.smartclassroom.api.uploadFile
import com.lixin.smartclassroom.api.yanxuecoursedetail
import com.lixin.smartclassroom.api.zhcoursedetail
import com.lixin.smartclassroom.api.zhuticoursedetail
import com.lixin.smartclassroom.bean.BiaoQianBean
import com.lixin.smartclassroom.bean.DataListBean
import com.lixin.smartclassroom.common.recyclerDialog
import com.lixin.smartclassroom.common.saveSuccessDialog
import com.lixin.smartclassroom.databinding.ActivityAddCourseTab2Binding
import com.lixin.smartclassroom.ui.home.adapter.oneText
import com.lixinkeji.base.BaseActivity
import com.lixinkeji.extension.getIntentString
import com.lixinkeji.extension.gone
import com.lixinkeji.extension.loadRound
import com.lixinkeji.extension.onClick
import com.lixinkeji.extension.start
import com.lixinkeji.extension.text
import com.lixinkeji.extension.toast
import com.lixinkeji.extension.visible
import com.lixinkeji.utils.GlideEngine
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import java.io.File
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Calendar
import java.util.Locale

/**
 * Description 编辑智慧课堂
 * Author: lwc
 * Date:2023/12/8 10:04
 */
class AddCourseAct : BaseActivity<ActivityAddCourseTab2Binding>() {
    override fun getViewBinding() = ActivityAddCourseTab2Binding.inflate(layoutInflater)

    override fun topBarHide() = false
    override fun startPadding() = true

    //    override fun title() = "编辑课程"
    override fun title(): String {
        isEdit = getIntentString("isEdit")
        return if (isEdit.isEmpty()) "创建课程"
        else "编辑课程"
    }

    private var localMediaList = ArrayList<LocalMedia>()
    private var hasSelectType = 0
    private var imgList = ArrayList<String>()
    private var imgListUrl = ArrayList<String>()
    private var listBean = ArrayList<DataListBean>()
    var size = 0
    private var taskType = ""
    private var courseid = ""
    private var isEdit = ""
    private var isCopy = ""
    private var files = ArrayList<File>()
    private var yinzhangUrl = ""
    private var yinzhangUrlId = ""
    private var baominginfoId = ""
    private var coverImgUrl = ""
    private var uploadFinishFlag = true
    private var courseLabelId = ""
    private var suoshuclassId = ""
    private var suoshufenleiId = ""
    private var yanxuenanduId = ""

    private var bianqiantype = ""

    override fun iniView() {
        taskType = getIntentString("type")
        courseid = getIntentString("courseid")
        isCopy = getIntentString("isCopy")
        if (isEdit == "1") {
            bianqiantype = "1"
            if (isCopy.isEmpty()) binding.btnAddChapter.gone()
            else binding.btnAddChapter.gone()
            setUI()
        }

        binding.apply {

            when (taskType) {
                "1" -> {
                    tvTitle.text = "课程名称"
                    etTitle.hint = "请输入课程名称"
                    llYanxue.gone()
                }

                "2" -> {
                    tvTitle.text = "场馆名称"
                    etTitle.hint = "请输入场馆名称"
                    llClassification.visible()
                    llYanxue.gone()
                    llFinishStyle.visible()
                }

                "3" -> {
                    llCourse.gone()
                    llYanxue.visible()
                    recycler.oneText(1)
                }
            }
        }

        receiveEvent<DataListBean>("courselable") {
            courseLabelId = it.id.toString()
        }
        receiveEvent<String>("updateBiaoqianType") {
            bianqiantype = "2"
        }
        receiveEvent<DataListBean>("suoshuclass") {
            suoshuclassId = it.id.toString()
        }
        receiveEvent<DataListBean>("suoshufenlei") {
            suoshufenleiId = it.id.toString()
        }
        receiveEvent<DataListBean>("yanxuenandu") {
            yanxuenanduId = it.id.toString()
        }
        receiveEvent<DataListBean>("yinzhangUrl") {
            yinzhangUrl = it.imageurl.toString()
            yinzhangUrlId = it.id.toString()
            binding.imgStyle.loadRound(yinzhangUrl)
        }
        receiveEvent<String>("baominginfoId") {
            baominginfoId = it
        }
    }

    private fun setUI() {
        binding.apply {
            scopeNetLife {
                when (taskType) {
                    "1" -> {
                        val baseBean = zhcoursedetail(courseid)
                        if (baseBean.result == "0") {
                            etTitle.setText(baseBean.title)
                            tvDate.text = baseBean.fabutime
                            tvClass.text = baseBean.classesname
                            tvSubject.text = baseBean.lablename
                            suoshuclassId = baseBean.suoshuclass!!
                            courseLabelId = baseBean.courselable!!
                            coverImgUrl = baseBean.coerimage!!
                            val localMedia = LocalMedia()
                            localMedia.realPath = baseBean.coerimage
                            localMediaList.add(localMedia)
                            coverImg.loadRound(baseBean.coerimage, 10)
                        }
                    }

                    "2" -> {
                        val baseBean = zhuticoursedetail(courseid)
                        if (baseBean.result == "0") {
                            etTitle.setText(baseBean.title)
                            tvDate.text = baseBean.fabutime
                            tvClass.text = baseBean.classesname
                            tvSubject.text = baseBean.lablename
                            tvClassification.text = baseBean.fenleiname
                            imgStyle.loadRound(baseBean.icon!!, 10, true)
                            suoshuclassId = baseBean.suoshuclass!!
                            courseLabelId = baseBean.courselable!!
                            coverImgUrl = baseBean.coerimage!!
                            yinzhangUrl = baseBean.icon!!

                            suoshufenleiId = baseBean.fenleiid!!
                            coverImgUrl = baseBean.coerimage!!
                            yinzhangUrlId = baseBean.iconid.toString()
                            val localMedia = LocalMedia()
                            localMedia.realPath = baseBean.coerimage
                            localMediaList.add(localMedia)
                            coverImg.loadRound(baseBean.coerimage!!, 10)
                        }
                    }

                    "3" -> {
                        val baseBean = yanxuecoursedetail(courseid)
                        if (baseBean.result == "0") {
                            etTitle.setText(baseBean.title)
                            tvDifficulty.text = baseBean.nandu
                            tvStartTime.text = baseBean.begintime
                            coverImg.loadRound(baseBean.image!!, 10)
                            // TODO: 添加研学详情信息
                            etYanxue.setText(baseBean.title)
                            tvInformation.text = baseBean.baominginfoname
                            baominginfoId = baseBean.baominginfo.toString()
                            val labelList = baseBean.biaoqian
                            if (labelList != null) {
                                for (i in labelList.indices) {
                                    if (courseLabelId.isEmpty()) {
                                        courseLabelId = labelList[i].id.toString()
                                    } else {
                                        courseLabelId += "," + labelList[i].id.toString()
                                    }
                                }
                            }
                            recycler.oneText(1).models = labelList
                            yanxuenanduId = baseBean.nanduid!!
                            baominginfoId = baseBean.baominginfo!!
                            coverImgUrl = baseBean.image

                            tvEndTime.text = baseBean.baomingend
                            tvClass.text = baseBean.classesname
                            tvSubject.text = baseBean.lablename
                            val localMedia = LocalMedia()
                            localMedia.realPath = baseBean.coerimage
                            localMediaList.add(localMedia)
                        } else {
                            toast(baseBean.resultNote.toString())
                        }
                    }
                }

            }
        }
    }


    override fun onClick() {
        binding.apply {
            coverImg.onClick {
                selectPicture(2)
            }

            binding.tvDate.onClick {
                chooseDate("选择上课时间", binding.tvDate.text.toString(), binding.tvDate)
            }

            binding.btnSave.onClick {
                saveData(2)
            }

            binding.btnChangeClass.onClick {
                recyclerDialog(1, "选择所属班级", "取消", "确定", textView = binding.tvClass)
            }

            binding.btnChangeSubject.onClick {
                recyclerDialog(2, "选择课程标签", "取消", "确定", textView = binding.tvSubject)
            }
            binding.btnChangeClassification.onClick {
                recyclerDialog(
                    3, "选择所属分类", "取消", "确定", textView = binding.tvClassification
                )
            }

            binding.btnChangeInformation.onClick {
                recyclerDialog(
                    8, "选择报名信息", "取消", "确定", textView = binding.tvInformation
                )
            }

            binding.btnChangeStyle.onClick {
                recyclerDialog(7, "选择印章样式", "取消", "确定", recyclerView = recycler)
            }

            btnChangeDifficulty.onClick {
                recyclerDialog(4, "选择研学难度", "取消", "确定", textView = tvDifficulty)
            }

            btnChangeLabel.onClick {
                recyclerDialog(5, "选择研学标签", "取消", "确定", recyclerView = recycler)
            }
            btnChangeEndTime.onClick {
                chooseDate("选择报名截止时间", binding.tvEndTime.text.toString(), binding.tvEndTime)
            }

            btnChangeStartTime.onClick {
                chooseDate(
                    "选择报名开始时间", binding.tvStartTime.text.toString(), binding.tvStartTime
                )
            }

            btnAddChapter.onClick {
                saveData(1)
            }

        }
    }

    //operatorType 1--新增  2--保存
    private fun saveData(operatorType: Int) {
        binding.apply {
            val bubbleDialog = BubbleDialog(this@AddCourseAct)
            scopeDialog(bubbleDialog) {
                if (uploadFinishFlag) {
                    when (taskType) {
                        "1" -> {
                            if (etTitle.text().isEmpty()) {
                                toast("请输入标题")
                                return@scopeDialog
                            }
                            if (tvDate.text.toString() == "请选择上课时间") {
                                toast("请选择上课时间")
                                return@scopeDialog
                            }
                            if (tvClass.text.toString() == "请选择班级") {
                                toast("请选择班级")
                                return@scopeDialog
                            }
                            if (tvSubject.text.toString() == "请选择课程标签") {
                                toast("请选择课程标签")
                                return@scopeDialog
                            }
                            if (isCopy == "1") {
                                updatecourse(
                                    courseid,
                                    "2",
                                    etTitle.text(),
                                    tvDate.text.toString(),
                                    suoshuclassId,
                                    courseLabelId,
                                    coverImgUrl
                                )
                                saveSuccessDialog("复制成功")
                            } else if (isEdit.isEmpty()) {
                                val baseBean = addcourse(
                                    etTitle.text(),
                                    tvDate.text.toString(),
                                    suoshuclassId,
                                    courseLabelId,
                                    coverImgUrl
                                )
                                if (baseBean.result == "0") {
                                    saveSuccessDialog("智慧课程添加成功")
                                    courseid = baseBean.id.toString()
                                } else {
                                    toast(baseBean.resultNote.toString())
                                }
                            } else {
                                updatecourse(
                                    courseid,
                                    "1",
                                    etTitle.text(),
                                    tvDate.text.toString(),
                                    suoshuclassId,
                                    courseLabelId,
                                    coverImgUrl
                                )
                                saveSuccessDialog("修改成功")
                            }

                        }

                        "2" -> {
                            if (etTitle.text().isEmpty()) {
                                toast("请输入场馆名称")
                                return@scopeDialog
                            }
                            if (tvDate.text.toString() == "请选择上课时间") {
                                toast("请选择上课时间")
                                return@scopeDialog
                            }
                            if (tvClassification.text.toString() == "请选择所属分类") {
                                toast("请选择所属分类")
                                return@scopeDialog
                            }
                            if (tvClass.text.toString() == "请选择所属班级") {
                                toast("请选择所属班级")
                                return@scopeDialog
                            }

                            if (tvSubject.text.toString() == "请选择课程标签") {
                                toast("请选择课程标签")
                                return@scopeDialog
                            }
                            if (yinzhangUrl.isEmpty()) {
                                toast("请选择完成印章样式")
                                return@scopeDialog
                            }

                            if (isCopy == "1") {
                                updatezhuticourse(
                                    courseid,
                                    etTitle.text(),
                                    tvDate.text.toString(),
                                    suoshufenleiId,
                                    suoshuclassId,
                                    courseLabelId,
                                    yinzhangUrlId,
                                    coverImgUrl,
                                    "2"
                                )
                                saveSuccessDialog("复制成功")
                            } else if (isEdit.isEmpty()) {
                                val baseBean = addchangguan(
                                    etTitle.text(),
                                    tvDate.text.toString(),
                                    suoshufenleiId,
                                    suoshuclassId,
                                    courseLabelId,
                                    yinzhangUrlId,
                                    coverImgUrl
                                )
                                if (baseBean.result == "0") {
                                    saveSuccessDialog("场馆课程添加成功")
                                    courseid = baseBean.id.toString()
                                } else {
                                    toast(baseBean.resultNote.toString())
                                }
                            } else {
                                updatezhuticourse(
                                    courseid,
                                    etTitle.text(),
                                    tvDate.text.toString(),
                                    suoshufenleiId,
                                    suoshuclassId,
                                    courseLabelId,
                                    yinzhangUrlId,
                                    coverImgUrl,
                                    "1"
                                )
                                saveSuccessDialog("修改成功")
                            }


                        }

                        "3" -> {
                            var yanxueLabel = ""
                            if (recycler.bindingAdapter.models != null && recycler.bindingAdapter.models?.size!! > 0) {
                                for (i in 0 until recycler.bindingAdapter.models?.size!!) {
                                    if (bianqiantype == "1") {
                                        if (i == 0) {
                                            yanxueLabel =
                                                (recycler.bindingAdapter.models!![i] as BiaoQianBean).id.toString()
                                        } else {
                                            yanxueLabel += "," + (recycler.bindingAdapter.models!![i] as BiaoQianBean).id.toString()
                                        }
                                    } else {
                                        if (i == 0) {
                                            yanxueLabel =
                                                (recycler.bindingAdapter.models!![i] as DataListBean).id.toString()
                                        } else {
                                            yanxueLabel += "," + (recycler.bindingAdapter.models!![i] as DataListBean).id.toString()
                                        }
                                    }
                                }
                            }

                            if (etYanxue.text().isEmpty()) {
                                toast("请输入研学名称")
                                return@scopeDialog
                            }
                            if (tvDifficulty.text.toString() == "请选择研学难度") {
                                toast("请选择研学难度")
                                return@scopeDialog
                            }
                            if (tvInformation.text.toString() == "请选择报名所需信息") {
                                toast("请选择报名所需信息")
                                return@scopeDialog
                            }

                            if (yanxueLabel.isEmpty()) {
                                toast("请选择研学标签")
                                return@scopeDialog
                            }
                            if (tvStartTime.text.toString() == "请选择开始时间") {
                                toast("请选择开始时间")
                                return@scopeDialog
                            }

                            if (tvEndTime.text.toString() == "请选择报名截止时间") {
                                toast("请选择报名截止时间")
                                return@scopeDialog
                            }

                            if (isCopy == "1") {
                                updateyanxuecourse(
                                    courseid,
                                    etYanxue.text(),
                                    yanxuenanduId,
                                    yanxueLabel,
                                    tvStartTime.text.toString(),
                                    tvEndTime.text.toString(),
                                    coverImgUrl,
                                    "2"
                                )
                                saveSuccessDialog("复制成功")
                            } else if (isEdit.isEmpty()) {
                                val baseBean = addyanxuecourse(
                                    etYanxue.text(),
                                    yanxuenanduId,
                                    yanxueLabel,
                                    baominginfoId,
                                    tvStartTime.text.toString(),
                                    tvEndTime.text.toString(),
                                    coverImgUrl
                                )
                                if (baseBean.result == "0") {
                                    saveSuccessDialog("研学课程添加成功")
                                    courseid = baseBean.id.toString()
                                } else {
                                    toast(baseBean.resultNote.toString())
                                }
                            } else {
                                updateyanxuecourse(
                                    courseid,
                                    etYanxue.text(),
                                    yanxuenanduId,
                                    yanxueLabel,
                                    tvStartTime.text.toString(),
                                    tvEndTime.text.toString(),
                                    coverImgUrl,
                                    "1"
                                )
                                saveSuccessDialog("修改成功")
                            }


                        }
                    }
                    when (operatorType) {
                        1 -> {
                            start(AddChapterAct::class.java) {
                                putExtra("type", taskType)
                                putExtra("courseid", courseid)
                            }
                            finish()
                        }

                        2 -> finish()
                    }

                }


            }
        }

    }

    private fun selectPicture(type: Int) {
        PictureSelector.create(this@AddCourseAct)
            .openGallery(SelectMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
            .setImageEngine(GlideEngine.createGlideEngine()).setMaxSelectNum(1)
            .setMinSelectNum(0)// 最小选择数量
            .setImageSpanCount(4)// 每行显示个数
            .setSelectionMode(SelectModeConfig.SINGLE)// 多选 or 单选PictureConfig.MULTIPLE : PictureConfig.SINGLE
            .isPreviewImage(true)// 是否可预览图片
            .isCameraAroundState(true)// 是否显示拍照按钮
            .isSelectZoomAnim(true)// 图片列表点击 缩放效果 默认true
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: java.util.ArrayList<LocalMedia>?) {

                    if (result != null) {
                        if (result.size > 0) {
                            uploadFinishFlag = false
                            if (type == 1) binding.imgStyle.loadRound(result[0].path!!, 10, true)
                            else binding.coverImg.loadRound(result[0].path!!, 10, true)
                            var file: File
                            if (result[0].path!!.contains("content:")) {
                                var res = ""
                                var proj = arrayOf(MediaStore.Images.Media.DATA)
                                val cursor = getContentResolver().query(
                                    Uri.parse(result[0].path!!), proj, null, null, null
                                );
                                if (cursor?.moveToFirst() == true) {
                                    val column_index =
                                        cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                                    res = cursor.getString(column_index);
                                }
                                cursor?.close()
                                file = File(res)
                            } else {
                                file = File(result[0].path!!)
                            }

                            scopeNetLife {
                                val baseBean = uploadFile(file)
                                if (baseBean.result == "0") {
                                    if (type == 1) yinzhangUrl = baseBean.url.toString()
                                    else coverImgUrl = baseBean.url.toString()

                                    uploadFinishFlag = true
                                }
                            }
                        }
                    }


                }

                override fun onCancel() {

                }
            })

    }

    /**
     * 选择生日
     * */
    private fun chooseDate(title: String, def: String, view: TextView) {
//        val format = "yyyy-MM-dd HH:mm:ss"
        val format = "yyyy-MM-dd"
        val selectedDate = Calendar.getInstance()
        if (def.isNotEmpty() && def != "请选择上课时间" && def != "请选择开始时间" && def != "请选择报名截止时间") {
            val df: DateFormat = SimpleDateFormat(format, Locale.getDefault())
            selectedDate.time = df.parse(def)
        }
//        val startDate = Calendar.getInstance()
//        val endDate = Calendar.getInstance()
//        startDate.set(startDate.get(Calendar.YEAR), 0, 1, 0, 0, 0)
//        endDate.set(
//            endDate.get(Calendar.YEAR)+1,
//            12,
//            endDate.get(Calendar.DAY_OF_MONTH),
//            endDate.get(Calendar.HOUR),
//            endDate.get(Calendar.MINUTE),
//            endDate.get(Calendar.SECOND)
//        )

        val mDatePickerView = TimePickerBuilder(this) { date, _ ->
            val df: DateFormat = SimpleDateFormat(format, Locale.getDefault())
            val time = df.format(date)
            view.text = time
        }.setType(booleanArrayOf(true, true, true, false, false, false))// 默认全部显示
            .setCancelText("取消")//取消按钮文字
            .setSubmitText("确定")//确认按钮文字
            .setContentTextSize(16)//滚轮文字大小
            .setTitleSize(15)//标题文字大小
            .setTitleText(title)//标题文字
            .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
            .isCyclic(false)//是否循环滚动
            .setTitleColor(Color.BLACK)//标题文字颜色
            .setSubmitColor(ContextCompat.getColor(this, R.color.color_blue_44))//确定按钮文字颜色
            .setCancelColor(ContextCompat.getColor(this, R.color.color_blue_44))//取消按钮文字颜色
            .setTitleColor(ContextCompat.getColor(this, R.color.color_black_33))
            .setTitleBgColor(Color.WHITE)//标题背景颜色
            .setBgColor(Color.WHITE)//滚轮背景颜色
            .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//            .setRangDate(startDate, endDate)//起始终止年月日设定
            .setLineSpacingMultiplier(2.5f).setLabel("", "", "", "", "", "")//默认设置为年月日时分秒
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .isDialog(false)//是否显示为对话框样式
            .build()
        if (!mDatePickerView!!.isShowing) mDatePickerView.show()
    }

}